package com.ken.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ken.dto.GoodsSalesDTO;
import com.ken.entity.Orders;
import com.ken.entity.User;
import com.ken.mapper.OrderMapper;
import com.ken.mapper.ReportMapper;
import com.ken.service.OrderService;
import com.ken.service.ReportService;
import com.ken.service.UserService;
import com.ken.service.WorkspaceService;
import com.ken.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.ken.entity.Orders.COMPLETED;

@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Orders> implements ReportService {
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getInfoTurnoverStatistics(LocalDate begin, LocalDate end) {
        //存入begin->end中的各个天数
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存储每天的营业额
        List<Double> dailyEarnList = new ArrayList<>();
        for (LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            List<Orders> orderListByDay = lambdaQuery()
                    .eq(Orders::getStatus, COMPLETED)
                    .ge(Orders::getOrderTime, beginTime)
                    .le(Orders::getOrderTime, endTime)
                    .list();
            double dailyEarn = orderListByDay.stream().map(Orders::getAmount).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
            dailyEarnList.add(dailyEarn);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(dailyEarnList,","))
                .build();

    }

    @Override
    public UserReportVO getInfoUserStatistics(LocalDate begin, LocalDate end) {
        //存入begin->end中的各个天数
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //存储每天的新增用户数
       List<Integer> newUserList = new ArrayList<>();
        //存储当天的用户总数
        List<String> totalUserList = new ArrayList<>();
        for (LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询当天新用户数量
            int size = userService.lambdaQuery()
                    .ge(User::getCreateTime, beginTime)
                    .le(User::getCreateTime, endTime).list().size();
            newUserList.add(size);
            //查询当天所有用户数量
            String string = userService.lambdaQuery()
                    .le(User::getCreateTime, endTime)
                    .count()
                    .toString();
            totalUserList.add(string);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {

        //日期列表，以逗号分隔
        List<LocalDate> dateList=new ArrayList<>();

        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //存放每天的订单总数，以逗号分隔,
        List<Integer> orderCountList=new ArrayList<>();

        //存放每天的有效订单数列表，以逗号分隔
        List<Integer> validOrderCountList=new ArrayList<>();

        //遍历dateList 集合 查询每天的有效订单数和订单总数
        for (LocalDate localDate : dateList) {

            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //查询每天订单总数
            Long count = orderService.lambdaQuery()
                    .ge(Orders::getOrderTime, beginTime)
                    .le(Orders::getOrderTime, endTime).count();

            //查询每天有效订单数
            int i = orderService.lambdaQuery()
                    .ge(Orders::getOrderTime, beginTime)
                    .le(Orders::getOrderTime, endTime)
                    .eq(Orders::getStatus, COMPLETED).count().intValue();

            orderCountList.add(Integer.valueOf(count.toString()));
            validOrderCountList.add(i);

        }

        //计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单总数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate=0.0;
        // 订单完成率 = 有效订单数 / 总订单数 * 100%
        if (totalOrderCount!=0){
            orderCompletionRate=validOrderCount.doubleValue() / totalOrderCount;
        }

        OrderReportVO build = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,",")) //日期
                .orderCountList(StringUtils.join(orderCountList,",")) //每日订单数
                .validOrderCountList(StringUtils.join(validOrderCountList,",")) //每日有效订单数
                .totalOrderCount(totalOrderCount)//订单总数
                .validOrderCount(validOrderCount)//有效订单数
                .orderCompletionRate(orderCompletionRate)//订单完成率
                .build();

        return build;
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        // 将传入的开始时间转化为 LocalDateTime，设置时间为一天的最小时间（00:00）
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);

        // 将传入的结束时间转化为 LocalDateTime，设置时间为一天的最大时间（23:59:59.999999999）
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        // 获取指定时间范围内 订单完成状态 下的销量Top10商品信息
        // SalesTop10 是一个包含商品名称和销量数量的 DTO（数据传输对象）列表
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop(beginTime, endTime, Orders.COMPLETED);

        // 使用 Java Stream API 获取销量Top10商品的名称列表
        List<String> nameList = salesTop10.stream()
                .map(GoodsSalesDTO::getName) // 提取商品名称
                .collect(Collectors.toList()); // 收集到 List 中

        // 使用 Java Stream API 获取销量Top10商品的销量列表
        List<Integer> numberList = salesTop10.stream()
                .map(GoodsSalesDTO::getNumber) // 提取商品销量数量
                .collect(Collectors.toList()); // 收集到 List 中

        // 封装并返回一个 SalesTop10ReportVO 对象，包含商品名称和销量列表
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList, ",")) // 将名称列表转化为逗号分隔的字符串
                .numberList(StringUtils.join(numberList, ",")) // 将销量列表转化为逗号分隔的字符串
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService
                .getBusinessData(LocalDateTime.of(begin,LocalTime.MIN)
                        , LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass()
                .getClassLoader()
                .getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            // 获取单元格
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //准备明细数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
